package com.bolt.report.engine.calculator;

import com.bolt.report.engine.BindData;
import com.bolt.report.engine.Calculator;
import com.bolt.report.engine.fill.FillContext;
import com.bolt.report.engine.fill.FillReturnValue;
import com.bolt.report.engine.model.Cell;
import com.bolt.report.engine.model.Expression.CalculatorExpression;
import com.bolt.report.util.ToolUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class MinCalculator implements Calculator {
    @Override
    public Object evaluate(FillContext context, BindData data, CalculatorExpression expr, Cell cell) {
        List<BigDecimal> result = new ArrayList<>();
        FillReturnValue values = context.getReturnValue(data.getKey());
        int start = data.start(), end = data.end();
        while (values.next(start, end)) {
            Object value = values.getValue(expr.getExpr());
            if (value == null || value.toString().equals("")) {
                continue;
            }
            result.add(ToolUtil.toBigDecimal(value));
        }
        return result.stream().mapToDouble(k->k.doubleValue()).min().orElse(0.00);
    }
}